<template>
  <div class="app-container">
    <h3>操作日志</h3>
     <el-col class="container-query" :span="8">
        <el-col class="mar-r__15" :span="14"><el-input v-model="query" ref="count" placeholder="搜索文章标题/用户ID"></el-input></el-col>
        <el-col :span="8">
          <el-button  type="primary" icon="plus" @click="queryInfo">查询
          </el-button>
        </el-col>
      </el-col>
    <el-table
    :data="tableData"
    border
    style="width: 100%">
    <el-table-column align="center" label="序号" width="80">
        <template slot-scope="scope">
          <span v-text="getIndex(scope.$index)" ></span>
        </template>
      </el-table-column>
    <el-table-column
      prop="nickname"
      label="用户姓名"
      width="180">
    </el-table-column>
    <el-table-column
      prop="username"
      label="用户ID">
    </el-table-column>
    <el-table-column
      prop="role_name"
      label="用户角色">
    </el-table-column>
    <el-table-column
      prop="articleTitle"
      label="所操作文章标题">
    </el-table-column>
    <el-table-column
      prop="status_code"
      label="操作类型">
      <template slot-scope="scope">
          <el-tag
            :type="dataColorFun(stateCode[scope.row.status_code]) ? 'success' : 'danger'" 
            close-transition>{{stateCode[scope.row.status_code]}}</el-tag>
        </template>
    </el-table-column>
    <el-table-column
      prop="createTime"
      label="操作时间">
    </el-table-column>
    <el-table-column label="查看所操作文章详情">
      <template slot-scope="scope">
          <el-button @click="lookUserInfoFun(scope.$index)">查看</el-button>
        </template>
    </el-table-column>
  </el-table>
  <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page.sync="listQuery.currentPage"
      :page-size="10"
      layout="prev, pager, next, jumper"
      :total="totalCount">
    </el-pagination>
  </div>
</template>
<script>
import { opcreateLog, dataColorFun } from '../../utils/state.code'
export default {
  data() {
    return {
      tableData: [],
      stateCode: opcreateLog,
      list: [], //表格的数据
      allPermission: [],
      listLoading: false, //数据加载等待动画
      dialogStatus: "create",
      dialogFormVisible: false,
      textMap: {
        update: "编辑",
        create: "新建角色"
      },
      tempRole: {
        roleName: "",
        roleId: "",
        permissions: []
      },
      adminName: "管理员",
      listQuery: {
          pageNum: 1,//页码
          pageRow: 10,//每页条数
        },
      totalCount: 0, //分页组件--数据总条数
      articleId:"",//文章ID
      query:""
    };
  },
  created() {
    // this.getList();
    // this.getAllPermisson();
    this.operationInfoFun()
  },
  methods: {
    getAllPermisson() {
      //查询所有权限
      this.api({
        url: "/role/listAllPermission",
        method: "get"
      }).then(data => {
        this.allPermission = data.list;
      });
    },
    getList() {
      //查询列表
      this.listLoading = true;
      this.api({
        url: "/role/listRole",
        method: "get"
      }).then(data => {
        this.listLoading = false;
        this.list = data.list;
      });
    },
    getIndex($index) {
      //表格序号
      return $index + 1;
    },
    showCreate() {
      //显示新增对话框
      this.tempRole.roleName = "";
      this.tempRole.roleId = "";
      this.tempRole.permissions = [];
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
    },
    showUpdate($index) {
      let role = this.list[$index];
      this.tempRole.roleName = role.roleName;
      this.tempRole.roleId = role.roleId;
      this.tempRole.permissions = [];
      for (let i = 0; i < role.menus.length; i++) {
        let perm = role.menus[i].permissions;
        for (let j = 0; j < perm.length; j++) {
          this.tempRole.permissions.push(perm[j].permissionId);
        }
      }
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
    },
    createRole() {
      if (!this.checkRoleNameUnique()) {
        return;
      }
      if (!this.checkPermissionNum()) {
        return;
      }
      //添加新角色
      this.api({
        url: "/role/add",
        method: "post",
        data: this.tempRole
      }).then(() => {
        this.getList();
        this.dialogFormVisible = false;
      });
    },
    updateRole() {
      if (!this.checkRoleNameUnique(this.tempRole.roleId)) {
        return;
      }
      if (!this.checkPermissionNum()) {
        return;
      }
      //修改角色
      this.api({
        url: "/role/update",
        method: "post",
        data: this.tempRole
      }).then(() => {
        this.getList();
        this.dialogFormVisible = false;
      });
    },
    checkPermissionNum() {
      //校验至少有一种权限
      if (this.tempRole.permissions.length === 0) {
        this.$message.error("请至少选择一种权限");
        return false;
      }
      return true;
    },
    checkRoleNameUnique(roleId) {
      //校验名称重复
      let roleName = this.tempRole.roleName;
      if (!roleName) {
        this.$message.error("请填写角色名称");
        return false;
      }
      let roles = this.list;
      let result = true;
      for (let j = 0; j < roles.length; j++) {
        if (
          roles[j].roleName === roleName &&
          (!roleId || roles[j].roleId !== roleId)
        ) {
          this.$message.error("角色名称已存在");
          result = false;
          break;
        }
      }
      return result;
    },
    removeRole($index) {
      let _vue = this;
      this.$confirm("确定删除此角色?", "提示", {
        confirmButtonText: "确定",
        showCancelButton: false,
        type: "warning"
      }).then(() => {
        let role = _vue.list[$index];
        _vue
          .api({
            url: "/role/delete",
            method: "post",
            data: {
              roleId: role.roleId
            }
          })
          .then(() => {
            _vue.getList();
          })
          .catch(e => {});
      });
    },
    isMenuNone(_index) {
      //判断本级菜单内的权限是否一个都没选
      let menu = this.allPermission[_index].permissions;
      let result = true;
      for (let j = 0; j < menu.length; j++) {
        if (this.tempRole.permissions.indexOf(menu[j].id) > -1) {
          result = false;
          break;
        }
      }
      return result;
    },
    isMenuAll(_index) {
      //判断本级菜单内的权限是否全选了
      let menu = this.allPermission[_index].permissions;
      let result = true;
      for (let j = 0; j < menu.length; j++) {
        if (this.tempRole.permissions.indexOf(menu[j].id) < 0) {
          result = false;
          break;
        }
      }
      return result;
    },
    checkAll(_index) {
      //点击菜单   相当于全选按钮
      let v = this;
      if (v.isMenuAll(_index)) {
        //如果已经全选了,则全部取消
        v.noPerm(_index);
      } else {
        //如果尚未全选,则全选
        v.allPerm(_index);
      }
    },
    allPerm(_index) {
      //全部选中
      let menu = this.allPermission[_index].permissions;
      for (let j = 0; j < menu.length; j++) {
        this.addUnique(menu[j].id, this.tempRole.permissions);
      }
    },
    noPerm(_index) {
      //全部取消选中
      let menu = this.allPermission[_index].permissions;
      for (let j = 0; j < menu.length; j++) {
        let idIndex = this.tempRole.permissions.indexOf(menu[j].id);
        if (idIndex > -1) {
          this.tempRole.permissions.splice(idIndex, 1);
        }
      }
    },
    addUnique(val, arr) {
      //数组内防重复地添加元素
      let _index = arr.indexOf(val);
      if (_index < 0) {
        arr.push(val);
      }
    },
    checkRequired(_perm, _index) {
      //本方法会在勾选状态改变之后触发
      let permId = _perm.id;
      if (this.tempRole.permissions.indexOf(permId) > -1) {
        //选中事件
        //如果之前未勾选本权限,现在勾选完之后,tempRole里就会包含本id
        //那么就要将必选的权限勾上
        this.makeReuqiredPermissionChecked(_index);
      } else {
        //取消选中事件
        if (_perm.requiredPerm === 1) {
          //如果是必勾权限,就把本菜单的权限全部移出
          //(其实也可以提示用户本权限是菜单里的必选,请先取消勾选另外几个权限,交互太麻烦,此处就直接全部取消选中了)
          this.noPerm(_index);
        }
      }
    },
    makeReuqiredPermissionChecked(_index) {
      //将本菜单必选的权限勾上
      let menu = this.allPermission[_index].permissions;
      for (let j = 0; j < menu.length; j++) {
        let perm = menu[j];
        if (perm.requiredPerm === 1) {
          //找到本菜单的必选权限,将其勾上
          this.addUnique(perm.id, this.tempRole.permissions);
        }
      }
    },
    //操作日志信息
    operationInfoFun(){
      this.api({
          url: "/article/operationLog",
          method: "get",
          params: {
            pageNum:this.listQuery.pageNum,
            pageRow:'10',
            condition:this.query
          }
        }).then(data => {
          this.totalCount = data.totalCount
          this.tableData = data.list
        })
    },
    // 查看用户信息
    lookUserInfoFun(index){
      this.api({
          url: "/article/articleDetail",
          method: "post",
          data: {
            articleId:this.tableData[index].articleId
          }
        }).then(data => {
          this.$router.push({path: '/user/details'});
          sessionStorage.setItem("articleId",this.tableData[index].articleId)
          sessionStorage.setItem("type","log")
        })
    },
    handleSizeChange(val) {
        //改变每页数量
        this.listQuery.pageRow = val
        this.handleFilter();
      },
      handleCurrentChange(val) {
        //改变页码
        this.listQuery.pageNum = val
        this.operationInfoFun();
      },
      handleFilter() {
        //查询事件
        this.listQuery.pageNum = 1
        this.operationInfoFun()
      },
      getIndex($index) {
        //表格序号
        return (this.listQuery.pageNum - 1) * this.listQuery.pageRow + $index + 1
      },
      dataColorFun,
      //查询
      queryInfo(){
        this.api({
          url: "/article/operationLog",
          method: "get",
          params: {
            pageNum:this.listQuery.pageNum,
            pageRow:'10',
            condition:this.query
          }
        }).then(data => {
          this.totalCount = data.totalCount
          this.tableData = data.list
        })
      }
    },
    watch: {
    //watch()监听某个值（双向绑定）的变化，从而达到change事件监听的效果
      query: {
        handler: function() {
          var _this = this;
          _this.number = _this.$refs.count.value.length;
          if(_this.number==1){
            this.operationInfoFun()
          }
        },
        deep: true
    }
  }
};
</script>
<style scoped>
.requiredPerm {
  color: #ff0e13;
}
.container-query{
  float: right;
  margin-bottom: 20px;
}
</style>
